package com.longqin.wechat.service.impl;

import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.interfaces.Claim;
import com.longqin.wechat.entity.AccessToken;
import com.longqin.wechat.entity.MyException;
import com.longqin.wechat.entity.User;
import com.longqin.wechat.entity.WxAccessToken;
import com.longqin.wechat.entity.WxUserInfo;
import com.longqin.wechat.jwt.JWTUtil;
import com.longqin.wechat.mapper.WxUserMapper;
import com.longqin.wechat.service.CommSerive;
import com.longqin.wechat.service.UserService;
import com.longqin.wechat.service.WxService;
import com.longqin.wechat.util.MD5Util;
import com.longqin.wechat.util.MyObjectUtil;
import com.longqin.wechat.util.ResponseEnum;


/**
 * @Description: 账号接口实现类
 * @Author longqin
 * @Date 2025-05-07
 * 
 */
@Service
public class UserServiceImpl extends CommSerive implements UserService{
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Resource
	private WxService wxService;
	
	@Resource
	private WxUserMapper wxUserMapper;

	@Override
	public AccessToken authorization(String code) throws Exception {
		WxAccessToken atm = wxService.getOpenId(code);
		String openId = atm.getOpenid();
		User user = wxUserMapper.selectUserInfoByOpenId(openId);
		if(null == user) throw new MyException(ResponseEnum.NOTFOUND.getCode(), openId); // 未绑定返回openId
		return getAccessToken(user, openId, false);	
	}
	
	@Override
	@Transactional
	public AccessToken login(String userName, String password, String openId) throws Exception {
		User user = wxUserMapper.selectByUserName(userName);
		if(null == user) throw new MyException(ResponseEnum.ERROR.getCode(), "账号不存在");
		if(!MyObjectUtil.isNotNull(openId) || openId.equals("undefined")) throw new MyException(ResponseEnum.ERROR.getCode(), "请输入正确的openid");
		if(!user.getPassword().equals(MD5Util.md5(password)))throw new MyException(ResponseEnum.ERROR.getCode(), "密码错误");
	    return getAccessToken(user, openId, true);
	}
	
	/**
	 * @Description: 获取用户微信信息以及token
	 * @param user
	 * @param openId
	 * @return
	 * @throws Exception
	 * @Author longqin
	 * @Date 2025-05-07
	 * 
	 */
	private AccessToken getAccessToken(User user, String openId, boolean isInsert)throws Exception{
		WxUserInfo wxui = wxService.getUserInfo(wxService.getAccessToken(), openId);
	    logger.info("wxui:{}",JSON.toJSON(wxui));
	    if(isInsert) wxUserMapper.insertIgnoreUserOpenId(user.getUserId(), openId,wxui.getUnionId(), wxui.getNickName(), wxui.getHeadimgurl());
	    user.setWeChatUserInfo(wxui);
		return JWTUtil.getAccessToken(user);
	}

	@Override
	public AccessToken refreshToken(String refresh_token) throws Exception {
		 Map<String,Claim> map = JWTUtil.getJWTClaim(refresh_token); // 从token中获取用户信息
		if(map.get("tokenType").asString().equals("refresh_token") && JWTUtil.verify(refresh_token)){
			return JWTUtil.refreshToken(refresh_token);
		}else throw new MyException(ResponseEnum.TOKENEXPIRED.getCode(), "refresh_token过期");
	}

	@Override
	public boolean wxLogout(String openId) throws Exception {
		if(openId.equals("undefined")) throw new MyException(ResponseEnum.ERROR.getCode(), "请输入正确的openid");
		Map<String,Claim> map = getUserClaims();
		if(null != map){
			return wxUserMapper.deleteByUserIdAndOpenId(map.get("userId").asInt(), openId)>=0;
		}else throw new MyException(ResponseEnum.NOTFOUND.getCode(), "token有误");//未绑定返回openId
	}
}
